package com.xiaojie.summer.server;

import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.resource.Resource;

/**
 * @author Nick
 * @date 2021/5/23
 * @description
 */
public class JettyServer {

    private int serverPort = 1996;
    private String staticPath = "webapp";
    private String serverPath = "/";
    private String[] welcomeFiles = new String[]{"index.html"};

    public void startServer(Class loadClass, Handler summerServletContextHandler) {
        Server server = new Server(serverPort);

        // 静态资源处理器
        ResourceHandler resourceHandler = new ResourceHandler();
        resourceHandler.setDirectoriesListed(true);
        resourceHandler.setBaseResource(Resource.newResource(loadClass.getClassLoader().getResource(staticPath)));
        resourceHandler.setWelcomeFiles(welcomeFiles);

        ServletContextHandler servletContextHandler = new ServletContextHandler(server, serverPath);
        HandlerCollection list = new HandlerCollection();
        list.addHandler(resourceHandler);

        /**
         * summer 的 Handler
         */
        if (summerServletContextHandler != null) {
            list.addHandler(summerServletContextHandler);
        }

        servletContextHandler.setHandler(list);

        server.setHandler(servletContextHandler);
        try {
            server.start();
            server.join();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
